package javalight.network.ro.server;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.xsocket.connection.INonBlockingConnection;

/**
 * 连接分发器
 * 分发处理当前可用连接
 * @author Ruby
 *
 */
public class ConnectionDispatcher {

	int dataBufferSize = 1024*10;
	Map<String, DataStore> handlerStore = new HashMap<String, DataStore>();	
	ExecutorService threadPool = Executors.newFixedThreadPool(20);
	
	public ConnectionDispatcher(int dataBufferSize)
	{
		this.dataBufferSize = dataBufferSize;
	}
	
	private DataStore getDataStore(INonBlockingConnection connection)
	{
		DataStore store = handlerStore.get(connection.getId());
		if(store==null)
		{
			store = new DataStore(connection, dataBufferSize);
			handlerStore.put(connection.getId(), store);
		}
		return store;
	}
	
	/**
	 * 分发连接，交给数据缓冲器处理
	 * @param connection
	 */
	public void dispatchData(INonBlockingConnection connection)
	{
		threadPool.execute(getDataStore(connection));
	}
}
